package com.freeman.boot.utils;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author freeman
 * @version 1.0
 * @since 2017/3/31
 */
public class WebHttpClientUtils {


    private static Logger logger = LoggerFactory.getLogger(WebHttpClientUtils.class);    //日志记录

    private static volatile CloseableHttpClient instance;

    public static CloseableHttpClient getInstance() {
        if (instance == null) {
            synchronized (WebHttpClientUtils.class) {
                if (instance == null) {
                    instance = newInstance();
                }
            }
        }
        return instance;
    }

    public static CloseableHttpClient newInstance() {
        return HttpClients.createDefault();
    }

    public static String get(String url) {
        String result = null;
        HttpGet get = new HttpGet(url);
        try {
            CloseableHttpResponse httpResponse = getInstance().execute(get);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(httpResponse.getEntity());
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return result;
    }
}
